﻿
function ShowTree() {

	var formObj = $("form");
	if (formObj.length == 0) {
		Alert("页面缺少必要的form标签");
		return false;
	}
	
	//******************************************************
	
	if(typeof treeData != "undefined")
	{
		var input = document.createElement("input");
		input.type = "hidden";
		input.name = "treeData";
		treeData = decodeURIComponent(treeData);
		input.value = treeData;
		formObj.append($(input));
	}
	else
	{
		alert("没有treeData！");
		return false;
	}
	
	if(typeof initData != "undefined")
	{
		var input = document.createElement("input");
		input.type = "hidden";
		input.name = "initData";
		initData = decodeURIComponent(initData);
		input.value = initData;
		formObj.append($(input));
	}
	else
	{
		alert("没有initData！");
		return false;
	}
	
	if(typeof topLevelValue != "undefined")
	{
		var input = document.createElement("input");
		input.type = "hidden";
		input.name = "topLevelValue";
		input.value = topLevelValue;
		formObj.append($(input));
	}
	else
	{
		alert("没有topLevelValue！");
		return false;
	}
	
	if(typeof isLazy != "undefined")
	{
		var input = document.createElement("input");
		input.type = "hidden";
		input.name = "isLazy";
		input.value = isLazy;
		formObj.append($(input));
	}
	
	if(typeof initData != "undefined")
	{
		var input = document.createElement("input");
		input.type = "hidden";
		input.name = "initData";
		input.value = initData;
		formObj.append($(input));
	}
	
	if(typeof selectType != "undefined")
	{
		var input = document.createElement("input");
		input.type = "hidden";
		input.name = "selectType";
		input.value = selectType;
		formObj.append($(input));
	}
	
	if(typeof expandType != "undefined")
	{
		var input = document.createElement("input");
		input.type = "hidden";
		input.name = "expandType";
		input.value = expandType;
		formObj.append($(input));
	}
	
	if(typeof onlyLeafSelect != "undefined")
	{
		var input = document.createElement("input");
		input.type = "hidden";
		input.name = "onlyLeafSelect";
		input.value = onlyLeafSelect;
		formObj.append($(input));
	}
	
	//******************************************************
	
	$("#"+FormTreeId).css("display","none");
	$("#"+FormTreeId).load(RootPath+ "/components/tree/tree",
		function(response, status) {
			if (status == "success") {
				
				var dpObj = $(response);
				
				var tempHtml = response;
				tempHtml=tempHtml.replace(/\%/g, "%25");
				tempHtml=tempHtml.replace(/\+/g, "%2B");
				tempHtml=tempHtml.replace(/\&/g, "%26");
				tempHtml = encodeURIComponent(tempHtml);
				
				$.ajax({
					type : "POST",
					url : FormCodeUrl + TreeQuery + "?tempHtml=" + tempHtml,
					data : formObj.serialize(),
					success : function(msg) {
						
						$("#"+FormTreeId).html("");
						var obj=$(msg);
						$("#"+FormTreeId).append(obj);
						$("#"+FormTreeId).css("display","");
						InitTree();
					}

				});
				
				
			}
		}
	);
}

function PrintSelectBox() {
    var temp = GetTemp();

    var selectObj = $("#SelectContainer");
    selectObj.empty();

    var html = "";
    var count = TreeSelectObject.length;

    for (var i = 0; i < count; i++) {
        var currentTemp = temp;
        var id = TreeSelectObject[i].NodeId;
               
        currentTemp = currentTemp.replace("{NodeId}", id);
        currentTemp = currentTemp.replace("{NodeText}", TreeSelectObject[i].NodeText);

        var newObj = $(currentTemp);
        var deleteObj = newObj.find(".Delete");
        var upObj = newObj.find(".Up");
        var downObj = newObj.find(".Down");

        deleteObj.bind("click", { id: id }, function(event) {
            DeleteOne(event.data.id);
        });

        upObj.bind("click", { id: id }, function(event) {
            alert("开发中。。。");
        });

        downObj.bind("click", { id: id }, function(event) {
            alert("开发中。。。");
        });

        selectObj.append(newObj);

    }

    //计算布局
    CalcForm(selectObj);
    //CalcChildElement(selectObj);
}


function DeleteOne(NodeId) {
    UnSelectItem(NodeId);
}

function GetTemp() {

    var t = "";
    t += "<div class=\"selectitem fullwidth h30\">";
    t += "<div class=\"calcwidth fullheight\">";
    t += "<font class=\"SelectTitle\"><a href=\"#text_{NodeId}\">{NodeText}</a></font>";
    t += "</div>";
    t += "<div class=\"fullheight w30\">";
    t += "<font class=\"SelectButton fullwidth Up\">上移</font>";
    t += "</div>";
    t += "<div class=\"fullheight w30\">";
    t += "<font class=\"SelectButton fullwidth Down\">下移</font>";
    t += "</div>";
    t += "<div class=\"fullheight w30\">";
    t += "<font class=\"SelectButton fullwidth Delete\">删除</font>";
    t += "</div>";
    t += "</div>";

    return t;
}








var TreeSelectObject = new Array();

function InitTree() {

    var selectButtons = $(".SelectButton");
    for (var i = 0; i < selectButtons.length; i++) {
        var number = selectButtons[i].id;
        number = number.replace("control_", "");
        
        //给checkbox和radio初始化赋值
        var controlObj=document.getElementById("control_"+number);
        if(controlObj)
        {
        	for(var j=0;j<TreeSelectObject.length;j++)
        	{
        		if(TreeSelectObject[j].NodeId==number)
        		{
        			if (controlObj.checked == false) {
                        controlObj.checked = true;
                    }
        		}
        	}
        }
        
        selectButtons[i].onclick = function() {
            //单选或多选
            var number = this.id.replace("control_", "");
            var type = $(this).attr("type");

            var currentObj = $(this);
            if (currentObj.is(":checked")) {
                SelectItem(number, type);
            }
            else {
                UnSelectItem(number, type);
            }
        }

        var expanyObj = document.getElementById("expand_" + number);
        if (expanyObj) {
            expanyObj.onclick = function() {
                var number = this.id.replace("expand_", "");

                var currentObj = $(this);

                if (currentObj.hasClass("Close")) {
                    HideItem(number);
                }
                else if (currentObj.hasClass("Open")) {
                    ShowItem(number);
                }
                else if (currentObj.hasClass("Init")) {
                    LoadItem(number);
                }
            }
        }
    }
    
    /*
	for(var i=0;i<TreeSelectObject.length;i++)
	{
		SelectItem(TreeSelectObject[i].NodeId);	
	}
	*/

}

function ShowItem(number) {
    //伸展必须一层一层
    $("#node_" + number + " .TreeItems:first").css("display", "");
    $("#node_" + number + " .Open:first").attr("class", "Button Close");
}

function HideItem(number) {
    //收缩可以整体
    $("#node_" + number + " .TreeItems").css("display", "none");
    $("#node_" + number + " .Close").attr("class", "Button Open");
}

function SelectItem(number, type) {

    var controlObj = document.getElementById("control_" + number);
    if (controlObj) {

        if (type == "radio") {
            ClearObject();
        }

        var selectValue = controlObj.value;
        //alert(decodeURIComponent(selectValue));
        selectValue = decodeURIComponent(selectValue)
        var selectObj = eval("(" + selectValue + ")");
        AddObject(selectObj);

        if (controlObj.checked == false) {
            controlObj.checked = true;
        }
    }
}

function UnSelectItem(number, type) {

    var controlObj = document.getElementById("control_" + number);
    if (controlObj) {
        var selectValue = controlObj.value;
        selectValue = decodeURIComponent(selectValue)
        var selectObj = eval("(" + selectValue + ")");
        RemoveObject(selectObj);

        if (controlObj.checked) {
            controlObj.checked = false;
        }
    }
}

function AddObject(selectObj) {
    var count = TreeSelectObject.length;
    TreeSelectObject[count] = selectObj;

    PrintSelectBox();
}

function RemoveObject(selectObj) {
    var count = TreeSelectObject.length;
    var index = -1;
    for (var i = 0; i < count; i++) {
        if (selectObj.NodeId == TreeSelectObject[i].NodeId) {
            index = i;
        }
    }
    if (index >= 0) {
        for (var i = index; i < count; i++) {
            if (i == (count - 1)) {
                TreeSelectObject[i] = undefined;
            }
            else {
                TreeSelectObject[i] = TreeSelectObject[i + 1];
            }
        }
        TreeSelectObject.length = count - 1;
    }

    PrintSelectBox();
}

function ClearObject() {
    TreeSelectObject.length = 0;
}

function LoadItem(number) {

    var expandObj = $("#expand_" + number);
    var ajaxUrl = unescape(expandObj.attr("AjaxFileName"));
    var isLast = expandObj.attr("IsLast");
    var preLine = expandObj.attr("PreLine");

    if (isLast == undefined) {
        isLast = "";
    }
    if (preLine == undefined) {
        preLine = "";
    }

    var paramArray = ajaxUrl.split(/[?&=]/);
    var hashTable = getHashTable(paramArray);

    //WebService访问，处理url参数

    var data = "";
    if (hashTable.length > 0) {
        for (var i = 0; i < hashTable.length; i++) {
            data += ",";
            data += "'" + hashTable[i].key + "':'" + hashTable[i].value + "'";
        }
        //固定项
        data += ",";
        data += "'islast':'" + isLast + "'";
        data += ",";
        data += "'preline':'" + preLine + "'";
        data = data.substring(1);
    }
    data = "{" + data + "}";

    $.ajax({
        type: "POST",
        url: hashTable.url + "/TreeAjax",
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function(msg) {
            var treeHTML = msg.d;

            if (treeHTML.length > 0) {
                $("#node_" + number + " .TreeItems").append(treeHTML);
                $("#node_" + number + " .TreeItems").css("display", "");
                $("#node_" + number + " .Init:first").attr("class", "Button Close");
            }
            else {
                $("#node_" + number + " .Init:first").attr("class", "Button");
            }

            //绑定事件
            $("#node_" + number + " .TreeItems .Init").click(function() {
                var id = $(this)[0].id.replace("expand_", "");

                var buttonObj = $($(this)[0].outerHTML);

                if (buttonObj.hasClass("Init")) {
                    LoadItem(id);
                }
                else if (buttonObj.hasClass("Close")) {
                    HideItem(id);
                }
                else if (buttonObj.hasClass("Open")) {
                    ShowItem(id);
                }
            });

        }
    });

}

function getHashTable(paramArray) {

    var list = new Array();
    list.url = paramArray[0];
    for (var i = 1; i < paramArray.length; i += 2) {
        var item = new Object();
        item.key = paramArray[i];
        item.value = paramArray[i + 1];

        list[(i - 1) / 2] = item;
    }

    return list;
}